package com.holly.aop;

import com.holly.mapper.EmpLoginLogMapper;
import com.holly.pojo.Emp;
import com.holly.pojo.EmpLoginLog;
import com.holly.pojo.LoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author holly
 * @create 2025-07-08 15:37
 */
@Slf4j
@Aspect
@Component
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Pointcut("execution(* com.holly.service.EmpService.login(..))")
    public void pt() {}

    @Around("pt()")
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        LocalDateTime currentDateTime = LocalDateTime.now();
        EmpLoginLog empLoginLog = new EmpLoginLog();

        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        // 获取登录方法参数（第一个参数应是Emp对象）
        Emp emp = (Emp) pjp.getArgs()[0];
        empLoginLog.setUsername(emp.getUsername());
        empLoginLog.setCostTime(end - start);
        empLoginLog.setLoginTime(currentDateTime);
        empLoginLog.setPassword(emp.getPassword());

        if (result instanceof LoginInfo) {
            LoginInfo loginInfo = (LoginInfo) result;
            log.info("员工登录成功，JWT令牌：{}", loginInfo.getToken());
            empLoginLog.setIsSuccess((short) 1);
            empLoginLog.setJwt(loginInfo.getToken());
            log.info("员工登录成功，{}", empLoginLog);
            empLoginLogMapper.insert(empLoginLog);
        } else {
            log.info("员工登录失败或未返回有效的LoginInfo对象");
            empLoginLog.setIsSuccess((short) 0);
            log.info("员工登录失败，{}", empLoginLog);
            empLoginLogMapper.insert(empLoginLog);
        }
        return result;
    }
}